<template>
  <!-- @change="handleChange" -->
  <section class="ant-upload">
    <a-upload
      v-model:file-list="props.fileList"
      list-type="picture-card"
      :before-upload="beforeUpload"
      :customRequest="handleRequestUpload"
      @preview="handlePreview"
      :max-count="1"
    >
      <!-- <img v-if="imageUrl" :src="imageUrl" alt="图片" />-->
      <div>
        <loading-outlined v-if="loading"></loading-outlined>
        <plus-outlined v-else />
        <div style="margin-top: 8px">Upload</div>
      </div>
    </a-upload>
    <!-- 图片放大 -->
    <a-modal :visible="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="imageUrl" />
    </a-modal>
  </section>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { message } from 'ant-design-vue';
import { Md5 } from 'ts-md5/dist/md5';
import { useNow, useDateFormat } from '@vueuse/core';
import type { UploadChangeParam, UploadProps } from 'ant-design-vue';
import OSS from 'ali-oss';
import oss from '@/utils/oss';
const props = defineProps({
  fileList: Array,
});
// const fileList = ref<UploadProps['fileList']>([]);
const imageUrl = ref<string>('');
const loading = ref<boolean>(false);
const previewVisible = ref(false);
const previewTitle = ref('');
const md5Format = Md5.hashStr(useDateFormat(useNow(), 'YYYY-MM-DD HH:mm:ss').value);
//上传前回调
const beforeUpload = (file: UploadProps['fileList'][number]) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
  if (!isJpgOrPng) {
    message.error('您上传的图片类型不对,请上传png、jpeg、jpg图片!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('请上传2MB内的图片!');
  }
  return isJpgOrPng && isLt2M;
};
//改变的回调
const handleRequestUpload = (info: UploadChangeParam) => {
  loading.value = true;
  const file = info.file;
  const client = new OSS(oss.ossParameter);
  const storeAs = `images/${useDateFormat(useNow(), 'YYYY-MM-DD').value}` + md5Format + '&xbdoss' + file.name;
  client.multipartUpload(storeAs, file, {}).then((result: any) => {
    props.fileList?.push({
      uid: result.res.requestUrls[0],
      name: result.name,
      url: `${oss.url}/${result.name}`,
    });

    loading.value = false;
  });
  props.fileList = props.fileList?.filter((v) => v.status !== 'uploading');
};
//点击图片
const handlePreview = async (file: UploadProps['fileList'][number]) => {
  previewTitle.value = file.url.split('&xbdoss')[1].split('.')[0];
  imageUrl.value = file.url;
  previewVisible.value = true;
};
//关闭图片放大
const handleCancel = () => {
  previewVisible.value = false;
};
</script>
